package com.beadwallet.alarm.service.wechat.impl;

import com.alibaba.fastjson.JSONObject;
import com.beadwallet.alarm.config.WeChatParames;
import com.beadwallet.alarm.entity.wechat.Text;
import com.beadwallet.alarm.entity.wechat.TextMessage;
import com.beadwallet.alarm.service.wechat.SendMessageService;
import com.beadwallet.alarm.util.WeChatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 发送消息实现类
 *
 * @author hyf
 * @date 2017/12/05
 */
@Service
public class SendMessageServiceImpl implements SendMessageService {

    private static Logger log = LoggerFactory.getLogger(SendMessageServiceImpl.class);

    @Override
    public JSONObject sendMessage(String accessToken, String content, String touser, String toparty) {

        //创建文本消息对象
        TextMessage textMessage = new TextMessage();

        //发送给id为touser的用户
        textMessage.setTouser(touser);
        //发送给id为toparty的部门(研发部)
        textMessage.setToparty(toparty);

        //消息类型
        textMessage.setMsgtype(WeChatParames.TEXT);
        //设置企业应用的Id
        textMessage.setAgentid(WeChatParames.AGENT_ID);

        Text text = new Text();
        text.setContent(content);
        textMessage.setText(text);
        //表示是否是保密消息，0表示否，1表示是，默认0
        textMessage.setSafe(WeChatParames.SAFE_0);

        JSONObject jsonObject;
        //1.获取json字符串：将message对象转换为json字符串
        String jsonMessage = JSONObject.toJSONString(textMessage);
        //获取请求的url
        String sendMessageUrl = WeChatParames.SENDMESSAGE_URL + accessToken;
        //调用接口发送信息
        jsonObject = WeChatUtil.httpRequest(sendMessageUrl, WeChatParames.POST, jsonMessage);
        log.info("调用微信响应结果:{}", jsonObject);

        //4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInteger(WeChatParames.ERRCODE)) {
                log.error("发送消息失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return jsonObject;
    }
}
